package tech.dnf.demo.rabbitmq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Consumer {
    private static final ExecutorService executor = Executors.newCachedThreadPool();
    private static Connection conn = null;
    private static Channel channel = null;

    public static final String PTPQ = "ptpq_1";
    private static QueueingConsumer ptpqConsumer = null;

    public static void main(String[] args) throws Exception {
        init();

        testPtpq();

        close();
    }

    private static void init() throws Exception {
        conn = ConnectionUtil.getConnection();
        channel = conn.createChannel();

        channel.queueDeclare(PTPQ, false, false, false, null);
        ptpqConsumer = new QueueingConsumer(channel);
        channel.basicConsume(PTPQ, true, ptpqConsumer);
//        ptpqConsumer.

    }

    private static void close() throws Exception {
        if (null != executor) {
            executor.shutdown();
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        }

        if (null != channel) {
            channel.close();
        }
        if (null != conn) {
            conn.close();
        }
    }

    private static void testPtpq() throws Exception {
        executor.execute(() -> {
            int i = 0;
            try {
                while (i++ <= 10) {
                    QueueingConsumer.Delivery delivery = null;
                    delivery = ptpqConsumer.nextDelivery();
                    String msg = new String(delivery.getBody());
                    System.out.println(msg);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }
}
